#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2011 - BidiX@BidiX.info
#
#
'''
	@author: BidiX
'''
import os, sys, re
from notewikiapp_client import Notewikiapp_Client

inline_rules = [
		# headings
		(r'^====== ======$', r'---'),
		(r'^======([^=]*)=*$', r'# \1'),
		(r'^=====([^=]*)=*$', r'# \1'),
		(r'^====([^=]*)=*$', r'## \1'),
		(r'^===([^=]*)=*$', r'### \1'),
		(r'^==([^=]*)=*$', r'#### \1'),
		(r'^=([^=]*)=*$', r'##### \1'),
		# external links
		(r'(https?:\/\/[^ \n]*)', r'<\1>'),
		# suppression tags
		(r'^ *{{tag>(.*)}} *', r''),
		# inline code
		(r'\'\'(.*)\'\'', r'`\`'),
		(r'^<code>$', '\n~~~~'),
		(r'^<\/code>$', '~~~~\n'),
		] 

def convertInline(line):
	for (pat, repl) in inline_rules:
		line = re.sub(pat, repl, line)
	return line

def convertList(line, first=False):
	line = re.sub(r'^  \* *', r'* ', line)
	line = re.sub(r'^   \* *', r'    * ', line)
	line = re.sub(r'^  - *', r'1. ', line)
	line = re.sub(r'^    - *', r'    1. ', line)
	return line
	
def convert(infile, name):
	'''
		inline : file
		return a dict {'name': name, 'title': title, 'text': text, 'tag': tag } 
	'''
	title = ''
	text = ''
	tag = 'dw, fixme'
	
	outlines = []
	mode = 'text'
	for line in infile:
		if mode == 'list' and line[:2] != '  ':
			# end list
			mode = 'text'
		if mode == 'text' and re.match(r'^   *(\*|-)', line):
			# begining list
			# add a blanc list
			mode = 'list'
			outlines.append("\n")
		if mode == 'list':
			line = convertList(line)
		if mode == 'text' or mode == 'list':
			m = re.search(r'{{tag>(.*)}}', line)
			if m and m.group(1):
				tag += ', ' + m.group(1).replace(' ', ', ')
			else:
				line = convertInline(line)
				if (not title) and (line[0:2] == "# "):
					title = line[2:].strip()
				outlines.append(line)
	outlines = clean(outlines)
	return {'name': name, 'title': title, 'text': ''.join(outlines), 'tag': tag.lower()}

def clean(outlines):
	# delete title line
	if re.match(r'^# ', outlines[0]):
		outlines.pop(0)
	if len(outlines) > 0:
		l = outlines[len(outlines)-1]
		if re.match(r'^ *$', outlines[len(outlines)-1]):
			outlines.pop()
		if re.match(r'^---$', outlines[len(outlines)-1]):
			outlines.pop()
	return outlines
	
		
def process_file(app, dir_in, dir_out, dirpath, file):
	print "about to post %s"%file
	print "in_filename : %s"%(dir_in+dirpath+'/'+file)
	print "out_filename: %s"%(dir_out+dirpath+'/'+ file.split('.')[0])
	infile = open(dir_in+dirpath+'/'+file, 'r')	
	outname = dir_out+dirpath+'/'+ file.split('.')[0]
	article = convert(infile, outname)
	infile.close()
	code, body = app.post_article(article['name'], article['title'], article['text'], article['tag'])
	print "%s posted . Return code : %s. Response %s "%(file, code, body)
	
def process_dir(app, dir_in, dir_out, dirpath):
	infiles = os.listdir(dir_in+dirpath)
	for file in infiles:
		if os.path.isfile(dir_in+dirpath+'/'+file):
			if file[0] != '.':	
				process_file(app, dir_in, dir_out, dirpath, file)
		else:
			process_dir(app, dir_in, dir_out, dirpath+'/'+file)
			

def main(argv):
	'''
	'''
	user = argv[1]
	password = argv[2]
	file_in = argv[3]
	dir_out = argv[4]
	app = Notewikiapp_Client(user, password, local=False)
	if os.path.isdir(file_in):
		process_dir(app, file_in, dir_out, '')
	else:
		f = file_in.split('/')
		filename = f[len(f)-1]
		dirpath = '/'.join(f[0:len(f)-1])
		process_file(app, dirpath, dir_out, '', filename)

if __name__ == '__main__':
	main(sys.argv)
